package com.xxm.thoughtworksdemo

import android.content.Context
import android.text.SpannableStringBuilder
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat

class CommentView : LinearLayout{
    private var mCommentBeans: List<CommentBean>? = null
    private var mLayoutParams: LayoutParams? = null
    private val mCommentVerticalSpace = dp2px(context,3f)

    constructor(context: Context?) : super(context)

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    fun addComments(commentBeans: List<CommentBean>?) {
        mCommentBeans = commentBeans
        if (commentBeans != null) {
            val oldCount = childCount
            val newCount = commentBeans.size
            if (oldCount > newCount) {
                removeViewsInLayout(newCount, oldCount - newCount)
            }
            for (i in 0 until newCount) {
                val hasChild = i < oldCount
                var childView: View? = if (hasChild) getChildAt(i) else null
                val commentBean: CommentBean = commentBeans[i]
                val commentSpan: SpannableStringBuilder = makeSingleCommentSpan(commentBean.sender.nick, commentBean.content)

                addViewInLayout(getTextView(commentSpan), i, getMarginLayoutParams(i), true)
                if (childView != null) {
                    removeViewInLayout(childView)
                }
            }
            requestLayout()
        }
    }

    private fun getTextView(content: SpannableStringBuilder): TextView {
        val textView = TextView(context)
        textView.setTextColor(ContextCompat.getColor(context, android.R.color.black))
        textView.textSize = 16f
        textView.setLineSpacing(mCommentVerticalSpace.toFloat(), 1f)
        textView.text = content
        return textView
    }

    private fun getMarginLayoutParams(index: Int): LayoutParams {
        if (mLayoutParams == null) {
            mLayoutParams = LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }
        if (mCommentBeans != null && index > 0) {
            mLayoutParams!!.bottomMargin =
                if (index == mCommentBeans!!.size - 1) 0 else mCommentVerticalSpace
        }
        return mLayoutParams!!
    }

}